<?php

namespace App\Http\Controllers\Goods;

use App\Http\Controllers\Controller;
use App\Models\Goods\Goods;
use App\Models\Goods\SeckillOrder;
use App\Server\RedisServer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SeckillController extends Controller
{

    /**
     * 下单减库存
     * http://www.test.com/seckill
     * @return string
     */
    public function seckill(){
        DB::beginTransaction();//开启事务
        try {
            $stock=DB::table('qiwei_goods')->value('stock');
            if ($stock>0){
//                DB::table('qiwei_goods')
//                    ->where('id',1)
//                    ->update(['stock'=> $stock-1]);
            Goods::where('id')->update(['stock'=>$stock-1]);

                DB::commit();
                return '秒杀成功';
            }
                return '秒杀失败';
        } catch (\Exception $exception){
            DB::rollBack();
            Log::info($exception->getMessage());
        }
    }

    /**
     * 支付减库存
     */
    public function payStock(){
        DB::beginTransaction();//开启事务
        try {
            $stock=DB::table('qiwei_goods')->value('stock');//查询商品表库存

    //      $stock=Goods::where('stock')->first();dd($stock);
            if ($stock>0){ //判断库存是否大于0
                Goods::where('id')->update(['stock'=>$stock-1]);//秒杀商品为1库存减1
                DB::commit();//事务提交
                return 'OK';
            }
        } catch (\Exception $exception){
            DB::rollBack();//事务回滚
            Log::info($exception->getMessage());//记录日志
        }
    }

    /**
     * 库存预热
     */
    public function preheatStock(){
//        DB::beginTransaction();
        $seckillGoodsId=1;
        $redisSeckillGoodsId='seckill_goods_list_'.$seckillGoodsId;
        $seckillGoodsId=1;//接收参数，预热秒杀商品id
        $redisSeckillGoodsId='seckill_goods_list_'.$seckillGoodsId;//redis中存储必须唯一

        //如果没有这个key先去数据库秒杀商品库存
        if (!RedisServer::getInstance()->exists($redisSeckillGoodsId)){
            $stock=DB::table('qiwei_goods')->value('stock');
            //秒杀商品库存存入到redis-list
            for($i=0;$i<$stock;$i++){
                RedisServer::getInstance()->rPush($redisSeckillGoodsId,1);
            }
        }
    }

    /**
     * 预扣库存
     */
    public function redisStock(){
        try {
            //秒杀商品ID
            $seckillGoodsId=1;
            $activityId=1;
            $userId=9527;
            //购买数量
            $num=1;
            //通过商品的id重新查一下商品的价格
            $originPrice=DB::table('seckill_goods')
                ->where('id',$seckillGoodsId)
                ->value('goods_price');//dd($originPrice);
            //计算总金额
            $totalPrice=($originPrice * 100) * $num / 100;
            $currentTime=date("Y-m-d H:i:s",time());//当前时间

            //秒杀商品库存
            $redisSeckillGoodsId='seckill_goods_list_'.$seckillGoodsId;
            //存放秒杀成功的用户
            $redisSeckillGoodsSet = 'seckill_goods_set_' . $seckillGoodsId;
            //判断用户是否参与秒杀
            if (RedisServer::getInstance()->sIsMember($redisSeckillGoodsSet,$userId)){
                return response()->json(['code'=>200,'msg'=>'您已参与过抢购，下次再会~~~','data'=>[]]);
            }
            //开启redis事务
            RedisServer::getInstance()->watch($redisSeckillGoodsId);

            //判断redis是否还有库存
            $redisStock=RedisServer::getInstance()->lLen($redisSeckillGoodsId);
            if ($redisStock>0){
                //如果库存大于0 弹出库存
                RedisServer::getInstance()->lPop($redisSeckillGoodsId);
                //创建订单
                $orderData=[
                    'order_number' => date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
                    'user_id'=>$userId,
                    'activity_id'=>$activityId,
                    'seckill_goods_id'=>$seckillGoodsId,
                    'original_price'=>$originPrice,
                    'total_price'=>$totalPrice,
                    'pay_method'=>0,
                    'status'=>0,
                    'address'=>json_encode([
                        'username'=>"上海",
                        'phone'=>"123456",
                        'address'=>"上海市奉贤区五四公路3389号"
                    ]),
                    'num'=>$num,
                    'created_at' => $currentTime,
                    'updated_at' => $currentTime,

                ];//
                $orderAdd=SeckillOrder::create($orderData);
                //异步记录秒杀记录表
                //在生成一个延迟队列，用于库存归还
                //如果已经参与过该商品的秒杀，就不能在次秒杀，怎么办 redis set集合（无序且唯一）
                RedisServer::getInstance()->sAdd($redisSeckillGoodsSet,$userId);
                //查询秒杀商品库存
                RedisServer::getInstance()->exec();
                return response()->json(['code'=>200,'msg'=>'秒杀成功','data'=>[$orderAdd]]);
            } else {
                return response()->json(['code'=>2001,'msg'=>'没有库存','data'=>[]]);
            }
                return response()->json(['code'=>2002,'msg'=>'秒杀失败！','data'=>[]]);

        } catch (\Exception $exception){
            Log::info($exception->getMessage());//记入日志
        }
    }



}
